package com.kedll.library.util;

import android.content.Context;
import android.text.format.DateFormat;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.kedll.library.KBaseApplication;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.Random;

public class OSSManager {
    private static final String TAG = "OSSManagerTag";
    private OSS mOSS;
    private static OSSManager mInstance;
    private static final String BUCKET_NAME = "ihome-zpzy-test";    //此处正式环境下需要去掉test：=> ihome-zpzy

    private Context context = KBaseApplication.getInstance();

    private String ossConfig = (String) SharePreUtils.getOssConfig();

    //单例模式
    public static OSSManager getInstance() {
        if (mInstance == null) {
            synchronized (OSSManager.class) {
                mInstance = new OSSManager();
            }
        }
        return mInstance;
    }

    public OSS getOSS() {
        if (mOSS == null) {
            OSSCredentialProvider provider = new OSSPlainTextAKSKCredentialProvider(getInstance().getOSSAK(), getInstance().getOSSSK());
            ClientConfiguration conf = new ClientConfiguration();
            conf.setConnectionTimeout(15 * 1000);   // 连接超时，默认15秒
            conf.setSocketTimeout(15 * 1000);       // socket超时，默认15秒
            conf.setMaxConcurrentRequest(5);        // 最大并发请求书，默认5个
            conf.setMaxErrorRetry(2);               // 失败后最大重试次数，默认2次
            mOSS = new OSSClient(context, "http://oss-cn-hangzhou.aliyuncs.com", provider, conf);
        }
        return mOSS;
    }

    /**
     *上传的方法
     * @param objectKey 标识
     * @param path      需上传文件的路径
     * @return 外网访问的路径
     */
    private static String upload(String objectKey, String path) {
        // 构造上传请求
        PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, objectKey, path);
        try {
            //得到client
            OSS client = getInstance().getOSS();
            //上传获取结果
            PutObjectResult result = client.putObject(request);
            //获取可访问的url
            String url = client.presignPublicObjectURL(BUCKET_NAME, objectKey);
            return url;
        } catch (ClientException | ServiceException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 上传普通图片
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadImage(String path) {
        Log.d(TAG, "uploadImage: objectKey === " + getObjectImageKey());
        return upload(getObjectImageKey(), path);
    }

    /**
     * 获取时间
     *
     * @return 时间戳 例如:20180501
     */
    private static String getDateString() {
        return DateFormat.format("yyyyMMdd", new Date()).toString();
    }

    /**
     * 返回key
     *
     * 本地路径
     * @return key
     * 格式: mall/android/20190724/1563940606888OyV9OCgZ8n78Qd3i2ggWXzFgsJ2SIVK5.png
     */
    private static String getObjectImageKey() {
        Date date = new Date(System.currentTimeMillis());
        String secondTimestampTwo = getSecondTimestampTwo(date);
        String dateString = getDateString();
        return String.format("mall/android/%s/%s", dateString, secondTimestampTwo + getUUIDByRules32Image());
    }

    /**
     * 上传到后台的图片的名称
     */
    public static String getUUIDByRules32Image() {
        StringBuffer generateRandStr = null;
        try {
            String rules = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            int rpoint = 0;
            generateRandStr = new StringBuffer();
            Random rand = new Random();
            int length = 32;
            for (int i = 0; i < length; i++) {
                rpoint = rules.length();
                int randNum = rand.nextInt(rpoint);
                generateRandStr.append(rules.substring(randNum, randNum + 1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (generateRandStr == null) {
            return "getUUIDByRules32Image.png";
        }
        return generateRandStr + ".png";
    }

    /**
     * 获取精确到秒的时间戳
     * @param date
     * @return
     */
    public static String getSecondTimestampTwo(Date date){
        if (null == date) {
            return "";
        }
        return String.valueOf(date.getTime());
    }

    /**
     * 获取OSS AK参数
     * @return
     */
    private String getOSSAK() {
        try {
            JSONObject jsonObject = new JSONObject(ossConfig);
            return jsonObject.getString("accessKeyId");
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取OSS SK参数
     * @return
     */
    private String getOSSSK() {
        try {
            JSONObject jsonObject = new JSONObject(ossConfig);
            return jsonObject.getString("accessKeySecret");
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取OSS ENDPOINT参数
     * @return
     */
    private String getOSSHost() {
        try {
            JSONObject jsonObject = new JSONObject(ossConfig);
            return jsonObject.getString("host");
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
}
